import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../system/fontsize_provider.dart';
import '../../services/auth_service.dart';
import '/models/LoadTaskData.dart';
import '../../utils/message_box.dart';
import '../../services/api_service.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class PutawaySummaryScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;

  const PutawaySummaryScreen({super.key, required this.jsonData});

  @override
  _PutawaySummaryScreenState createState() => _PutawaySummaryScreenState();
}

class _PutawaySummaryScreenState extends State<PutawaySummaryScreen> {
  // late PutawaySummaryData responseData;
  late Map<String, dynamic> orderDetails = {
    'Tasks': 0,
    'Locations': 0,
    'LPNS': 0,
    'Items': 0,
    'Eaches': 0,
  };
  late double _fontScale;
  late double labelFontSize = 12;
  late double textFontSize = 11;
  bool _isLoading = false;
  String? loadNumber;
  int? loadId;
  int? warehouseId;
  LoadTaskData? taskData;
  List<LoadLine> availableLpns = [];

  @override
  void initState() {
    super.initState();
    // 解析传入的参数（包含summaryData和loadTaskData）
    loadId = widget.jsonData['loadId'];
    loadNumber = widget.jsonData['loadNumber'];
    _initData();
  }

  // 异步初始化函数，处理getLoadLine调用
  Future<void> _initData() async {
    if (loadNumber == null) return; // 避免空值异常

    try {
      // 提前获取warehouseId
      final authService = Provider.of<AuthService>(context, listen: false);
      final user = authService.currentUser;
      warehouseId = user?.warehouse;

      // 等待异步结果
      final jsonData = await getLoadLine(loadNumber!);
      print('getLoadLine返回数据: $jsonData');

      // 解析数据并更新状态（确保组件未销毁）
      if (mounted) {
        // 修复：直接使用返回数据，无需再取['data']
        taskData = LoadTaskData.fromJson(jsonData);
        // 空值安全处理：如果loadLines为null则使用空列表
        availableLpns = taskData?.loadLines ?? [];

        Set<String> lpnSet = {};
        Set<String> itemSet = {};
        int totalEaches = 0;
        if (availableLpns.isNotEmpty) {
          for (var i in availableLpns) {
            if (i.lpnNumber != null && i.lpnNumber != 'N/A') {
              lpnSet.add(i.lpnNumber!);
            }
            if (i.itemNumber.trim().isNotEmpty) {
              itemSet.add(i.itemNumber.trim());
            }
            totalEaches += i.quantity;
          }
          
          setState(() {
            orderDetails = {
              'Tasks': availableLpns.length,
              'Locations': availableLpns.length,
              'LPNS': lpnSet.length,
              'Items': itemSet.length,
              'Eaches': totalEaches,
            };
          });
        }
      }
    } catch (e) {
      // 处理异常
      if (mounted) {
        MessageBox.showMessageBox(context, '初始化失败: $e', isError: true);
        setState(() => taskData = null); // 异常时重置状态
      }
    }
  }

  // 调用API获取详情数据
  Future<Map<dynamic, dynamic>> getLoadLine(String loadNumber) async {
    var apiUrl = ApiService.baseURL + ApiService.fetchLoad;

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }

    final responsedata = await http.get(
      Uri.parse(apiUrl + loadNumber),
      headers: {
        'Authorization': 'JWT $accessToken',
        'x-warehouse-id': '$warehouseId',
        'x-timezone': 'America/Los_Angeles',
        'Content-Type':'application/json',
        'X-Client-Type':'app'
      },
    );
    String responseBody = utf8.decode(responsedata.bodyBytes);
    Map<String, dynamic> jsonData = json.decode(responseBody);
    
    if(jsonData['code'] == 2000){
      return jsonData['data']; // 直接返回data字段内容
    }
    else if(jsonData['code'] == 401){
      AuthService auth = AuthService();
      auth.logout(context);
      throw Exception('The session has expired, Please log in again.');
    }
    else {
      throw Exception('${jsonData['msg']}');
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    // orderDetails = {
    //   'Tasks': responseData.tasks,
    //   'Locations': responseData.locations,
    //   'LPNS': responseData.lpns,
    //   'Items': responseData.items,
    //   'Eaches': responseData.totalEaches,
    // };

    return Scaffold(
      appBar: AppBar(
        title: Text('Putaway Summary', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            // 返回LoadTaskScreen并传递参数
            Navigator.pushNamed(
              context,
              '/inbound/load-task',
              arguments:{
                'loadNumber':loadNumber,
                'loadId':loadId,
              }
            );
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.symmetric(horizontal: 64, vertical: 32),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 订单信息部分
                  ..._buildOrderDetails(),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: _submitLpn,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: const EdgeInsets.symmetric(horizontal: 60, vertical: 16),
                      ),
                      child: Text(
                        'Start Putaway',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16 * _fontScale,
                          color: Colors.white
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  // 构建订单信息行
  List<Widget> _buildOrderDetails() {
    return orderDetails.entries.map((entry) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左侧标题
            SizedBox(
              width: 120,
              child: Text(
                '${entry.key}:',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: labelFontSize * _fontScale
                ),
              ),
            ),
            const SizedBox(width: 10),
            // 右侧值
            Expanded(
              child: Text(
                entry.value.toString(),
                style: TextStyle(fontSize: textFontSize * _fontScale),
              ),
            ),
          ],
        ),
      );
    }).toList();
  }

  // 提交LPN的方法
  void _submitLpn() {
    Navigator.pushNamed(
      context,
      '/inbound/putaway-tasks',
      arguments: {
        'loadNumber':loadNumber,
        'loadId':loadId,
      },
    );
  }
}
    